name: Test

on:
  schedule:
    - cron: 15,45 0-18,22-23 * * *
  push:
    branches:
      - master
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        include:
          - userName: q215613905
            repoName: TVBoxOS
            branchName: main
          - userName: takagen99
            repoName: Box
            branchName: main
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Check New Commit
        run: |
          upStream=https://github.com/${{ matrix.userName }}/${{ matrix.repoName }}
          echo "upStream=$upStream" >> $GITHUB_ENV
          commit=$(curl -sL $upStream/commits/${{ matrix.branchName }} |grep -o "/${{ matrix.userName }}/${{ matrix.repoName }}/commit/[a-z0-9]\+" |head -1 | cut -d\/ -f5)
          #if ! git log --oneline |grep -q "$commit"; then
          if ! grep -q "$commit" README.md; then
            echo "commit=$commit" >> $GITHUB_ENV
            echo "commitS=${commit:0:7}" >> $GITHUB_ENV
          fi
      - name: Checkout Source Code and Zip
        if: ${{ env.commit }}
        run: |
          git clone ${{ env.upStream }} TVBoxOSC
          cd TVBoxOSC
          git checkout ${{ env.commit }}
          echo "tag=$(git log --date=format:'%Y%m%d-%H%M' --pretty=format:%cd ${{ env.commitS }} -1)" >> $GITHUB_ENV
          zip -q -x ".git/*" -r ${{ env.commitS }}-source.zip .
      - uses: actions/cache@v3
        with:
          path: |
            ~/TVBoxOSC/.gradle/caches
            ~/TVBoxOSC/.gradle/wrapper
          key: ${{ runner.os }}-${{ matrix.userName }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
          restore-keys: |
            ${{ runner.os }}-${{ matrix.userName }}-
      - name: Release Apk Sign
        if: ${{ env.commit }}
        working-directory: TVBoxOSC
        run: |
          signingConfigs='ICAgIHNpZ25pbmdDb25maWdzIHtcCiAgICAgICAgaWYgKHByb2plY3QuaGFzUHJvcGVydHkoIlJFTEVBU0VfU1RPUkVfRklMRSIpKSB7XAogICAgICAgICAgICBteUNvbmZpZyB7XAogICAgICAgICAgICAgICAgc3RvcmVGaWxlIGZpbGUoUkVMRUFTRV9TVE9SRV9GSUxFKVwKICAgICAgICAgICAgICAgIHN0b3JlUGFzc3dvcmQgUkVMRUFTRV9TVE9SRV9QQVNTV09SRFwKICAgICAgICAgICAgICAgIGtleUFsaWFzIFJFTEVBU0VfS0VZX0FMSUFTXAogICAgICAgICAgICAgICAga2V5UGFzc3dvcmQgUkVMRUFTRV9LRVlfUEFTU1dPUkRcCiAgICAgICAgICAgICAgICB2MVNpZ25pbmdFbmFibGVkIHRydWVcCiAgICAgICAgICAgICAgICB2MlNpZ25pbmdFbmFibGVkIHRydWVcCiAgICAgICAgICAgICAgICBlbmFibGVWM1NpZ25pbmcgPSB0cnVlXAogICAgICAgICAgICAgICAgZW5hYmxlVjRTaWduaW5nID0gdHJ1ZVwKICAgICAgICAgICAgfVwKICAgICAgICB9XAogICAgfVwKXA=='
          signingConfig='ICAgICAgICAgICAgaWYgKHByb2plY3QuaGFzUHJvcGVydHkoIlJFTEVBU0VfU1RPUkVfRklMRSIpKSB7XAogICAgICAgICAgICAgICAgc2lnbmluZ0NvbmZpZyBzaWduaW5nQ29uZmlncy5teUNvbmZpZ1wKICAgICAgICAgICAgfVwK'
          signingConfigs="$(echo "$signingConfigs" |base64 -d )"
          signingConfig="$(echo "$signingConfig" |base64 -d )"
          sed -i -e "/defaultConfig {/i\\$signingConfigs " -e "/debug {/a\\$signingConfig " -e "/release {/a\\$signingConfig " app/build.gradle
          cp -f ${{ github.workspace }}/.github/workflows/TVBoxOSC.jks app/TVBoxOSC.jks
          sed -i '$a\RELEASE_STORE_FILE=./TVBoxOSC.jks'     ./gradle.properties
          sed -i '$a\RELEASE_KEY_ALIAS=TVBoxOSC'            ./gradle.properties
          sed -i '$a\RELEASE_STORE_PASSWORD=TVBoxOSC'       ./gradle.properties
          sed -i '$a\RELEASE_KEY_PASSWORD=TVBoxOSC'         ./gradle.properties
      - name: Build With Gradle
        if: ${{ env.commit }}
        working-directory: TVBoxOSC
        run: |
          chmod +x gradlew
          ./gradlew assemblerelease --build-cache --parallel --daemon --warning-mode all
      - name: Prepare App
        if: ${{ env.commit }}
        working-directory: TVBoxOSC
        run: |
          rm -rf apk/
          mkdir -p apk/
          for file in `find ~ -name "*release*.apk" -print`; do
            mv "$file" apk/TVBox_release_${{ env.tag }}.apk
          done
      - name: Upload App To Artifact
        uses: actions/upload-artifact@v3
        if: ${{ env.commit }}
        with:
          name: ${{ matrix.userName }}-${{ matrix.repoName }}
          path: TVBoxOSC/apk/*
      - name: Release and Upload Assets
        uses: softprops/action-gh-release@v1
        if: ${{ env.commit }}
        with:
          name: ${{ env.tag }}
          tag_name: ${{ env.tag }}
          body: "Credit: ${{ matrix.userName }}/${{ matrix.repoName }}\n
                 Commit: ${{ env.commit }}"
          files: |
            TVBoxOSC/apk/*
            TVBoxOSC/${{ env.commitS }}-source.zip
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - name: Post To Telegram
        if: ${{ env.commit }}
        run: |
          if [ -n "${{ secrets.CHANNEL_ID }}" ] && [ -n "${{ secrets.BOT_TOKEN }}" ]; then
            OUTPUT="${{ github.workspace }}/TVBoxOSC/apk/"
            export appRelease=$(find $OUTPUT -name "*release*.apk")
            export sourceCode="${{ github.workspace }}/TVBoxOSC/${{ env.commitS }}-source.zip"
            #lastCommit=`git log --oneline |grep -o '[a-z0-9]\{40\}' |head -1`
            lastCommit=$(grep "${{ matrix.userName }}\/${{ matrix.repoName }}" README.md |grep -o '[a-z0-9]\{40\}')
            cd TVBoxOSC
            export LESSCHARSET=utf-8
            if [ "${{ env.commit }}" == "${lastCommit}" ]; then
              COMMIT_MESSAGE="$(python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1]))"  "`git log --pretty=format:%B ${{ env.commitS }} -1 |sed -e 's# \{2,\}#\n#g' -e '/^Merge pull/d' -e 's#"#\\"#g' -e '/^$/d' |cat -n |sort -k2,2 -k1,1n |uniq -f1 |sort -k1,1n |cut -f2- `")"
            else
              COMMIT_MESSAGE="$(python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1]))"  "`git log --pretty=format:%B ${{ env.commitS }}...${lastCommit:0:7} |sed -e 's# \{2,\}#\n#g' -e '/^Merge pull/d' -e 's#"#\\"#g' -e '/^$/d' |cat -n |sort -k2,2 -k1,1n |uniq -f1 |sort -k1,1n |cut -f2- `")"
            fi
            if [ ${#COMMIT_MESSAGE} -gt 0 ] && [ ${#COMMIT_MESSAGE} -le 1024 ]; then
              ESCAPED="$(echo $COMMIT_MESSAGE |sed 's#%[eE]2[0-9a-zA-Z%]\{6\}##g')"
            else
              COMMIT_URL=${{ env.upStream }}/commits/${{ matrix.branchName }}
              ESCAPED="$(python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1]))" "$COMMIT_URL")"
            fi
            curl -v "https://api.telegram.org/bot${{ secrets.BOT_TOKEN }}/sendMediaGroup?chat_id=${{ secrets.CHANNEL_ID }}&media=%5B%7B%22type%22%3A%22document%22%2C%20%22media%22%3A%22attach%3A%2F%2FappRelease%22%7D%2C%7B%22type%22%3A%22document%22%2C%20%22media%22%3A%22attach%3A%2F%2FsourceCode%22%2C%20%22caption%22%3A%22Credit%3A%20%23${{ matrix.userName }}%20%0ACommit%3A%20${{ env.commit }}%0AChangelog%3A%0A${ESCAPED}%22%7D%5D" -F appRelease="@$appRelease" -F sourceCode="@$sourceCode"
          fi
      - name: Push to master
        if: ${{ env.commit }}
        run: |
          rm -rf TVBoxOSC
          sed -i "/${{ matrix.userName }}\/${{ matrix.repoName }}/s#Updated: [a-zA-Z0-9]*#Updated: ${{ env.commit }}#" README.md
          sed -i '/url =/d' ./.git/config
          git config --local user.name "github-actions[bot]"
          git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git remote set-url --add origin "https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}"
          git add --all
          git commit -m "${{ env.commit }}"
          git push -u -f origin master
